package com.lysj.bhp.app.controller;

import com.lysj.bhp.app.base.AppContent;
import com.lysj.bhp.app.dto.WalletRecordDto;
import com.lysj.bhp.app.util.ListSortUtil;
import com.lysj.bhp.app.vo.WalletInfoVo;
import com.lysj.bhp.app.vo.WalletRecordVo;
import com.lysj.bhp.coinexchange.domain.BhpcRecord;
import com.lysj.bhp.exchangerate.vo.MyBalanceVo;
import com.lysj.bhp.investment.domain.Reward;
import com.lysj.bhp.recharge.domain.RechargeRecord;
import com.lysj.bhp.system.domain.Verify;
import com.lysj.bhp.user.domain.User;
import com.lysj.bhp.user.util.MyWallet;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import com.lysj.bhp.util.web.SelectItem;
import com.lysj.bhp.wallet.domain.BhpcWallet;
import com.lysj.bhp.wallet.domain.BitCoinWallet;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import com.lysj.bhp.withdraw.domain.Poundage;
import com.lysj.bhp.withdraw.domain.WithDraw;
import com.lysj.bhp.withdraw.domain.WithDrawAddress;
import com.lysj.bhp.withdraw.vo.WithDrawRecordVo;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api/balance/wallet")
public class AppWalletInfoController extends AppContent {

    @Resource
    MyWallet myWallet;

    @PostMapping("/get_wallet_info")
    public Resp getWalletInfo(String email) {
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        //创建钱包信息对象,初始化数额的值
        WalletInfoVo walletInfoVo = new WalletInfoVo();
        walletInfoVo.setAvailBhpcBalanceCny(BigDecimal.ZERO);
        walletInfoVo.setAvailBhpcBalance(BigDecimal.ZERO);
        walletInfoVo.setAvailEthBalanceCny(BigDecimal.ZERO);
        walletInfoVo.setAvailEthBalance(BigDecimal.ZERO);
        walletInfoVo.setAvailBtcBalanceCny(BigDecimal.ZERO);
        walletInfoVo.setAvailBtcBalance(BigDecimal.ZERO);
        walletInfoVo.setTotalBalanceCny(BigDecimal.ZERO);
        //查询该邮箱的用户是否激活
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(walletInfoVo);
        }
        //获取该邮箱用户的钱包信息
        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(user.getUserId());
        if (null != bitCoinWallet) {
            walletInfoVo.setAvailBtcBalance(bitCoinWallet.getAvailBalance().setScale(6, RoundingMode.HALF_DOWN));
            walletInfoVo.setAvailBtcBalanceCny(bitCoinWallet.getAvailBalance().multiply(exchangeRateService.bitcoinToCnyRate()).setScale(6, RoundingMode.HALF_DOWN));
            walletInfoVo.setTotalBalanceCny(walletInfoVo.getTotalBalanceCny().add(walletInfoVo.getAvailBtcBalanceCny()).setScale(6, RoundingMode.HALF_DOWN));
        }
        EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(user.getUserId());
        if (null != ethereumWallet) {
            walletInfoVo.setAvailEthBalance(ethereumWallet.getAvailBalance().setScale(6, RoundingMode.HALF_DOWN));
            walletInfoVo.setAvailEthBalanceCny(ethereumWallet.getAvailBalance().multiply(exchangeRateService.ethToCnyRate()).setScale(6, RoundingMode.HALF_DOWN));
            walletInfoVo.setTotalBalanceCny(walletInfoVo.getTotalBalanceCny().add(walletInfoVo.getAvailEthBalanceCny()).setScale(6, RoundingMode.HALF_DOWN));
        }
        BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(user.getUserId());
        if (null != bhpcWallet) {
            walletInfoVo.setAvailBhpcBalance(bhpcWallet.getAvailBalance().setScale(6, RoundingMode.HALF_DOWN));
            walletInfoVo.setAvailBhpcBalanceCny(bhpcWallet.getAvailBalance().multiply(exchangeRateService.bhpcToCnyRate()).setScale(6, RoundingMode.HALF_DOWN));
            walletInfoVo.setTotalBalanceCny(walletInfoVo.getTotalBalanceCny().add(walletInfoVo.getAvailBhpcBalanceCny()).setScale(6, RoundingMode.HALF_DOWN));
        }
        return new Resp(walletInfoVo);
    }


    /**
     * @author drj
     * @date 2018/07/10 14:03
     * @Description:获取钱包地址
     */
    @PostMapping("/get_wallet_address")
    public Resp getWalletAddress(String email, int walletType) throws Exception {
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        if (ParamUtil.isBlack(walletType)) {
            return new Resp(Resp.PARAM_ERROR, "请输入钱包类型");
        }
        //查询该邮箱的用户是否激活
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp("");
        }
        if (10 == walletType) {
            BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(user.getUserId());
            if (null == bitCoinWallet) {
                bitCoinWallet = (BitCoinWallet) myWallet.createBitWallet(user.getUserId(), email).getObj();
            }
            return new Resp(bitCoinWallet.getLastAddress());
        }
        if (20 == walletType) {
            EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(user.getUserId());
            if (null == ethereumWallet) {
                ethereumWallet = (EthereumWallet) myWallet.createEthWallet(user.getUserId()).getObj();
            }
            return new Resp("0x" + ethereumWallet.getAddress());
        }
        if (100 == walletType) {
            BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(user.getUserId());
            if (null == bhpcWallet) {
                bhpcWallet = (BhpcWallet) myWallet.createBhpcWallet(user.getUserId());
            }
            return new Resp("0x" + bhpcWallet.getAddress());
        }
        return new Resp("");
    }


    /**
     * @author drj
     * @date 2018/07/10 14:03
     * @Description:获取钱包充值记录
     */
    @PostMapping("/get_wallet_recharge_record")
    public Resp getWalletRechargeRecord(WalletRecordDto model, String email) {
        Integer limit = 5;
        Integer page = 0;
        if (!ParamUtil.isBlack(model.getLimit())) {
            limit = Integer.parseInt(model.getLimit());
        }
        if (!ParamUtil.isBlack(model.getPage())) {
            page = Integer.parseInt(model.getPage());
        }

        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        List<WalletRecordVo> walletRecordVos = new ArrayList<>();
        //查询该邮箱的用户是否激活
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(walletRecordVos);
        }
        Pageable pageable = new PageRequest(page, limit, new Sort(Sort.Direction.DESC, "createTime"));
        model.setUserId(user.getUserId());
        Specification specification = ParamUtil.createSpecification(model);
        Page<RechargeRecord> rechargeRecordPage = rechargeRecordRepository.findAll(specification, pageable);
        for (RechargeRecord rechargeRecord : rechargeRecordPage.getContent()) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAddress(rechargeRecord.getAddress());
            walletRecordVo.setAmount(rechargeRecord.getPayAmount());
            walletRecordVo.setCoinType(rechargeRecord.getName());
            walletRecordVo.setOperationType("收");
            walletRecordVo.setCreateDate(rechargeRecord.getCreateTime());
            walletRecordVos.add(walletRecordVo);
        }
        Map<String, Object> respMap = new HashMap();
        respMap.put("totalpage", rechargeRecordPage.getTotalPages());
        respMap.put("rows", walletRecordVos);
        return new Resp(respMap);
    }


    /**
     * @author drj
     * @date 2018/07/10 14:03
     * @Description:获取钱包提币记录
     */
    @PostMapping("/get_wallet_withdraw_record")
    public Resp getWalletWithdrawRecord(WalletRecordDto model, String email) {
        Integer limit = 5;
        Integer page = 0;
        if (!ParamUtil.isBlack(model.getLimit())) {
            limit = Integer.parseInt(model.getLimit());
        }
        if (!ParamUtil.isBlack(model.getPage())) {
            page = Integer.parseInt(model.getPage());
        }

        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        List<WalletRecordVo> walletRecordVos = new ArrayList<>();
        //查询该邮箱的用户是否激活
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(walletRecordVos);
        }
        Pageable pageable = new PageRequest(page, limit, new Sort(Sort.Direction.DESC, "createDate"));
        model.setUserId(user.getUserId());
        Specification specification = ParamUtil.createSpecification(model);
        Page<WithDraw> withDrawPage = withdrawRepository.findAll(specification, pageable);
        for (WithDraw withDraw : withDrawPage.getContent()) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAddress(withDraw.getAddress());
            walletRecordVo.setAmount(withDraw.getAmount());
            walletRecordVo.setCoinType(withDraw.getName());
            walletRecordVo.setOperationType("转");
            walletRecordVo.setCreateDate(withDraw.getCreateDate());
            walletRecordVos.add(walletRecordVo);
        }
        Map<String, Object> respMap = new HashMap();
        respMap.put("totalpage", withDrawPage.getTotalPages());
        respMap.put("rows", walletRecordVos);
        return new Resp(respMap);
    }


    /**
     * @author drj
     * @date 2018/07/10 20:15
     * @Description:获取对应币种最新5条换币记录
     */
    @PostMapping("/show_coin_bhpc_record")
    public Resp withdraw(String email, int walletType) {  //10:比特币;20:以太坊;100:BHPC;
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        if (ParamUtil.isBlack(walletType)) {
            return new Resp(Resp.PARAM_ERROR, "请输入钱包类型");
        }

        List<WalletRecordVo> walletRecordVos = new ArrayList<>();
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(walletRecordVos);
        }
        PageRequest pr = new PageRequest(0, 5);
        List<BhpcRecord> bhpcRecordList = bhpcRecordRepository.findByUserIdAndTypeOrderByCreateDateDesc(user.getUserId(), walletType, pr);
        for (BhpcRecord bhpcRecord : bhpcRecordList) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAmount(bhpcRecord.getExchangeNum());
            walletRecordVo.setBhpcAmount(bhpcRecord.getBhpc());
            if (bhpcRecord.getType() == 10) {
                walletRecordVo.setCoinType("BTC");
            } else {
                walletRecordVo.setCoinType("ETH");
            }
            walletRecordVo.setOperationType("换");
            walletRecordVo.setCreateDate(bhpcRecord.getCreateDate());
            walletRecordVos.add(walletRecordVo);
        }
        return new Resp(walletRecordVos);
    }


    /**
     * @author drj
     * @date 2018/07/10 14:03
     * @Description:获取钱包换币记录
     */
    @PostMapping("/get_wallet_bhpc_record")
    public Resp getWalletBhpcRecord(WalletRecordDto model, String email) {
        Integer limit = 5;
        Integer page = 0;
        if (!ParamUtil.isBlack(model.getLimit())) {
            limit = Integer.parseInt(model.getLimit());
        }
        if (!ParamUtil.isBlack(model.getPage())) {
            page = Integer.parseInt(model.getPage());
        }

        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        List<WalletRecordVo> walletRecordVos = new ArrayList<>();
        //查询该邮箱的用户是否激活
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(walletRecordVos);
        }
        Pageable pageable = new PageRequest(page, limit, new Sort(Sort.Direction.DESC, "createDate"));
        model.setUserId(user.getUserId());
        Specification specification = ParamUtil.createSpecification(model);
        Page<BhpcRecord> bhpcRecordPage = bhpcRecordRepository.findAll(specification, pageable);
        for (BhpcRecord bhpcRecord : bhpcRecordPage.getContent()) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAmount(bhpcRecord.getExchangeNum());
            walletRecordVo.setBhpcAmount(bhpcRecord.getBhpc());
            if (bhpcRecord.getType() == 10) {
                walletRecordVo.setCoinType("BTC");
            } else {
                walletRecordVo.setCoinType("ETH");
            }
            walletRecordVo.setOperationType("换");
            walletRecordVo.setCreateDate(bhpcRecord.getCreateDate());
            walletRecordVos.add(walletRecordVo);
        }
        Map<String, Object> respMap = new HashMap();
        respMap.put("totalpage", bhpcRecordPage.getTotalPages());
        respMap.put("rows", walletRecordVos);
        return new Resp(respMap);
    }


    /**
     * @author drj
     * @date 2018/07/14 10:57
     * @Description:获取钱包所有记录
     */
    @PostMapping("/get_wallet_all_record")
    public Resp getWalletAllRecord(WalletRecordDto model, String email) {

        Integer limit = 5;
        Integer page = 0;
        if (!ParamUtil.isBlack(model.getLimit())) {
            limit = Integer.parseInt(model.getLimit());
        }
        if (!ParamUtil.isBlack(model.getPage())) {
            page = Integer.parseInt(model.getPage());
        }

        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }


        List<WalletRecordVo> walletRecordVos = new LinkedList<>();
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(walletRecordVos);
        }
        //获取用户所有充值记录
        List<RechargeRecord> rechargeRecordList = rechargeRecordRepository.findByUserId(user.getUserId());
        for (RechargeRecord rechargeRecord : rechargeRecordList) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAddress(rechargeRecord.getAddress());
            walletRecordVo.setAmount(rechargeRecord.getPayAmount());
            walletRecordVo.setCoinType(rechargeRecord.getName());
            walletRecordVo.setOperationType("收");
            walletRecordVo.setCreateDate(rechargeRecord.getCreateTime());
            walletRecordVos.add(walletRecordVo);
        }
        //获取用户所有提币记录
        List<WithDraw> withDrawList = withdrawRepository.findByUserId(user.getUserId());
        for (WithDraw withDraw : withDrawList) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAddress(withDraw.getAddress());
            walletRecordVo.setAmount(withDraw.getAmount());
            walletRecordVo.setCoinType(withDraw.getName());
            walletRecordVo.setOperationType("转");
            walletRecordVo.setCreateDate(withDraw.getCreateDate());
            walletRecordVos.add(walletRecordVo);
        }
        //获取用户所有理财记录
        List<BhpcRecord> bhpcRecordList = bhpcRecordRepository.findByUserId(user.getUserId());
        for (BhpcRecord bhpcRecord : bhpcRecordList) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAmount(bhpcRecord.getExchangeNum());
            walletRecordVo.setBhpcAmount(bhpcRecord.getBhpc());
            if (bhpcRecord.getType() == 10) {
                walletRecordVo.setCoinType("BTC");
            } else {
                walletRecordVo.setCoinType("ETH");
            }
            walletRecordVo.setOperationType("换");
            walletRecordVo.setCreateDate(bhpcRecord.getCreateDate());
            walletRecordVos.add(walletRecordVo);
        }
        //对walletRecordVos,按照时间排序
        ListSort(walletRecordVos);
        Map<String, Object> respMap = new HashMap();
        int count = walletRecordVos.size();
        respMap.put("totalpage", count % limit == 0 ? count / limit : count / limit + 1);
        //数据总数小于每页显示的数据条数
        if (page == 0) {
            if (count <= limit)  //数据总数小于每页显示的数据条数
            {
                //截止到总的数据条数(当前数据不足一页，按一页显示)，这样才不会出现数组越界异常
                respMap.put("rows", walletRecordVos.subList(0, count));
            } else {
                respMap.put("rows", walletRecordVos.subList(0, limit));
            }

        }
        //截取起始下标
        int fromIndex = page * limit;
        //截取截止下标
        int toIndex = page * limit + limit;
        //若当前请求条数小于等于总条数
        if (fromIndex <= count) {
            if (count < toIndex) {
                respMap.put("rows", walletRecordVos.subList(fromIndex, count));
            } else {
                respMap.put("rows", walletRecordVos.subList(page * limit, page * limit + limit));
            }
        } else {
            respMap.put("rows", "");
        }
        return new Resp(respMap);

    }


    /**
     * @author drj
     * @date 2018/07/10 20:28
     * @Description:获取单个钱包的所有记录
     */
    @PostMapping("/get_coin_all_record")
    public Resp getCoinAllRecord(WalletRecordDto model, String email) {

        Integer limit = 5;
        Integer page = 0;
        if (!ParamUtil.isBlack(model.getLimit())) {
            limit = Integer.parseInt(model.getLimit());
        }
        if (!ParamUtil.isBlack(model.getPage())) {
            page = Integer.parseInt(model.getPage());
        }

        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }


        List<WalletRecordVo> walletRecordVos = new LinkedList<>();
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(walletRecordVos);
        }
        //获取用户所有充值记录
        List<RechargeRecord> rechargeRecordList = rechargeRecordRepository.findByUserIdAndCoinTypeOrderByCreateTimeDesc(user.getUserId(), model.getWalletType());
        for (RechargeRecord rechargeRecord : rechargeRecordList) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAddress(rechargeRecord.getAddress());
            walletRecordVo.setAmount(rechargeRecord.getPayAmount());
            walletRecordVo.setCoinType(rechargeRecord.getName());
            walletRecordVo.setOperationType("收");
            walletRecordVo.setCreateDate(rechargeRecord.getCreateTime());
            walletRecordVos.add(walletRecordVo);
        }
        //获取用户所有提币记录
        List<WithDraw> withDrawList = withdrawRepository.findByUserIdAndTypeOrderByCreateDateDesc(user.getUserId(), model.getWalletType());
        for (WithDraw withDraw : withDrawList) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAddress(withDraw.getAddress());
            walletRecordVo.setAmount(withDraw.getAmount());
            walletRecordVo.setCoinType(withDraw.getName());
            walletRecordVo.setOperationType("转");
            walletRecordVo.setCreateDate(withDraw.getCreateDate());
            walletRecordVos.add(walletRecordVo);
        }
        //获取用户所有理财记录
        List<BhpcRecord> bhpcRecordList = bhpcRecordRepository.findByUserIdAndTypeOrderByCreateDateDesc(user.getUserId(), model.getWalletType());
        for (BhpcRecord bhpcRecord : bhpcRecordList) {
            WalletRecordVo walletRecordVo = new WalletRecordVo();
            walletRecordVo.setAmount(bhpcRecord.getExchangeNum());
            walletRecordVo.setBhpcAmount(bhpcRecord.getBhpc());
            if (bhpcRecord.getType() == 10) {
                walletRecordVo.setCoinType("BTC");
            } else {
                walletRecordVo.setCoinType("ETH");
            }
            walletRecordVo.setOperationType("换");
            walletRecordVo.setCreateDate(bhpcRecord.getCreateDate());
            walletRecordVos.add(walletRecordVo);
        }
        //对walletRecordVos,按照时间排序
        ListSort(walletRecordVos);
        Map<String, Object> respMap = new HashMap();
        int count = walletRecordVos.size();
        respMap.put("totalpage", count % limit == 0 ? count / limit : count / limit + 1);
        //数据总数小于每页显示的数据条数
        if (page == 0) {
            if (count <= limit)  //数据总数小于每页显示的数据条数
            {
                //截止到总的数据条数(当前数据不足一页，按一页显示)，这样才不会出现数组越界异常
                respMap.put("rows", walletRecordVos.subList(0, count));
            } else {
                respMap.put("rows", walletRecordVos.subList(0, limit));
            }

        }
        //截取起始下标
        int fromIndex = page * limit;
        //截取截止下标
        int toIndex = page * limit + limit;
        //若当前请求条数小于等于总条数
        if (fromIndex <= count) {
            if (count < toIndex) {
                respMap.put("rows", walletRecordVos.subList(fromIndex, count));
            } else {
                respMap.put("rows", walletRecordVos.subList(page * limit, page * limit + limit));
            }
        } else {
            respMap.put("rows", "");
        }
        return new Resp(respMap);

    }


    /**
     * @author drj
     * @date 2018/07/10 14:56
     * @Description:获取币种对BHPC的汇率,10:BTC,20:ETH
     */
    @PostMapping("get_coin_to_bhpc_rate")
    public Resp getCoinToBhpcRate(int walletType) {
        BigDecimal coinRate = new BigDecimal(BigInteger.ZERO);
        if (10 == walletType) {
            coinRate = exchangeRateService.getBitcoinToDollar().divide(exchangeRateService.getBhpcToDollar(), 6, BigDecimal.ROUND_DOWN);
        }
        if (20 == walletType) {
            coinRate = exchangeRateService.getEthereumToDollar().divide(exchangeRateService.getBhpcToDollar(), 6, BigDecimal.ROUND_DOWN);
        }
        return new Resp(coinRate);
    }


    /**
     * @author drj
     * @date 2018/07/10 15:29
     * @Description:获取提币所需的手续费
     */
    @PostMapping("get_poundage")
    public Resp getPoundage(int walletType) {
        Map<String, Object> map = new HashMap<>();
        if (ParamUtil.isBlack(walletType)) {
            return new Resp(Resp.PARAM_ERROR, "系统错误");
        }
        Poundage poundage = null;
        if (100 == walletType) {
            poundage = poundageRepository.findByTypeAndInfoStatus(walletType, 3);
        } else {
            //获取提币手续费
            poundage = poundageRepository.findByType(walletType);
        }
        if (null != poundage) {
            map.put("poundage", poundage.getTransferFee());
            map.put("miniNumber", poundage.getMiniNumber());
            map.put("maxNumber", poundage.getMaxNumber());
        } else {
            map.put("poundage", 0);
            map.put("miniNumber", 0);
            map.put("maxNumber", 0);
        }
        return new Resp(map);
    }


    @ApiOperation(value = "实际金额", notes = "需要币种类型,数量")
    @PostMapping("/actual_amount")
    public Resp actualAmount(int walletType, BigDecimal num) {
        if (null == num || num.compareTo(BigDecimal.valueOf(0)) == 0) {
            return new Resp(Resp.PARAM_ERROR, "数量不能为空");
        }
        if (num.compareTo(BigDecimal.valueOf(0)) == -1) {
            return new Resp(Resp.PARAM_ERROR, "请输入正确的数量");
        }

        BigDecimal bhpcNum = BigDecimal.valueOf(0);
        if (walletType == 10) {
            BigDecimal DollarNum = num.multiply(exchangeRateService.getBitcoinToDollar());
            bhpcNum = DollarNum.divide(exchangeRateService.getBhpcToDollar(), 6, BigDecimal.ROUND_DOWN);
        } else if (walletType == 20) {
            BigDecimal DollarNum = num.multiply(exchangeRateService.getEthereumToDollar());
            bhpcNum = DollarNum.divide(exchangeRateService.getBhpcToDollar(), 6, BigDecimal.ROUND_DOWN);
        } else {
            return new Resp(Resp.PARAM_ERROR, "币种类型错误");
        }
        Map<String, Object> map = new HashMap<>();
        //构建一个Vo,显示总资产跟算力币兑换比特币跟ETH汇率
        MyBalanceVo myBalanceVo = new MyBalanceVo();
        myBalanceVo.setBhpc2btc(exchangeRateService.getBhpcToDollar().divide(exchangeRateService.getBitcoinToDollar(), 6, BigDecimal.ROUND_DOWN));
        myBalanceVo.setBhpc2eth(exchangeRateService.getBhpcToDollar().divide(exchangeRateService.getEthereumToDollar(), 6, BigDecimal.ROUND_DOWN));
        map.put("myBalanceVo", myBalanceVo);
        map.put("bhpcNum", bhpcNum);
        return new Resp(map);
    }


    /**
     * @author drj
     * @date 2018/07/10 16:30
     * @Description:提币申请
     */
    @PostMapping("withdraw_apply_add")
    public Resp withdrawApplyAdd(String email, String withDrawAddressId, BigDecimal amount, int walletType, String tradePassword) {
        return appWithDrawApplyService.withdrawApplyAdd(email, withDrawAddressId, amount, walletType, tradePassword);
    }


    /**
     * @author drj
     * @date 2018/07/10 17:26
     * @Description:币币理财
     */
    @PostMapping("buy_bhpc")
    public Resp buyBhpc(String email, BigDecimal amount, int walletType) throws Exception {
        return appBuyBhpcService.buyBhpc(email, amount, walletType);
    }


    /**
     * @author drj
     * @date 2018/07/12 18:56
     * @Description:检测是否设置交易密码
     */
    @PostMapping("/trade_password_is_set")
    public Resp tradePasswordIsSet(String email) {  //10:比特币;20:以太坊;100:BHPC;
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }

        //查询该用户是否设置过交易密码
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(Resp.PARAM_ERROR, "后台查无此用户");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("tradePassword", "false");
        if (!ParamUtil.isBlack(user.getTradePassword())) {
            map.put("tradePassword", "true");
        }
        return new Resp(map);
    }


    @PostMapping("/get_withdraw_address")
    public Resp getWithdrawAddress(String email, int walletType) {  //10:比特币;20:以太坊;100:BHPC;
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        if (ParamUtil.isBlack(walletType)) {
            return new Resp(Resp.PARAM_ERROR, "请输入钱包类型");
        }
        //查询该用户是否设置过交易密码
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(Resp.PARAM_ERROR, "后台查无此用户");
        }

        List<WithDrawAddress> withDrawAddressList = withDrawAddressRepository.findByUserIdAndTypeAndStatus(user.getUserId(), walletType, 1);
        return new Resp(withDrawAddressList);
    }


    /**
     * @author drj
     * @date 2018/07/12 19:01
     * @Description:设置交易密码
     */
    @PostMapping("/trade_password_set")
    public Resp tradePasswordSet(String email, String tradePassword) {  //10:比特币;20:以太坊;100:BHPC;
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        if (ParamUtil.isBlack(tradePassword)) {
            return new Resp(Resp.PARAM_ERROR, "请输入交易密码");
        }
        //查询该用户是否设置过交易密码
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(Resp.PARAM_ERROR, "后台查无此用户");
        }
        user.setTradePassword(ParamUtil.md5(tradePassword));
        userRepository.save(user);
        return new Resp("设置成功");
    }

    @PostMapping("/email_binding")
    public Resp emailBinding(String email) {
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        //查询该用户是否设置过交易密码
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(Resp.PARAM_ERROR, "邮箱不存在,请到算力官网注册");
        }
        return new Resp("绑定成功");
    }


    /**
     * @author drj
     * @date 2018/07/12 19:02
     * @Description:添加提币地址
     */
    @PostMapping("/withdraw_address_add")
    public Resp withdrawAddressAdd(String addressLabel, String address, int walletType, String email) {

        if (ParamUtil.isBlack(addressLabel)) {
            return new Resp(Resp.PARAM_ERROR, "标签不能为空");
        }
        if (ParamUtil.isBlack(address)) {
            return new Resp(Resp.PARAM_ERROR, "地址不能为空");
        }
        if (ParamUtil.isBlack(email)) {
            return new Resp(Resp.PARAM_ERROR, "请输入邮箱");
        }
        if (ParamUtil.isBlack(walletType)) {
            return new Resp(Resp.PARAM_ERROR, "系统错误");
        }
        //查询该用户是否设置过交易密码
        User user = userRepository.findByEmail(email);
        if (null == user) {
            return new Resp(Resp.PARAM_ERROR, "后台查无此用户");
        }

        //判定用户添加的提币地址是否大于5
        List<WithDrawAddress> queryWithDrawAddressList = withDrawAddressRepository.findByUserIdAndTypeAndStatus(user.getUserId(), walletType, 1);
        if (queryWithDrawAddressList.size() >= 5) {
            return new Resp(Resp.PARAM_ERROR, "钱包最大提币地址为5个");
        }

        //查询该用户相对应的币种的提币地址是否重复
        List<WithDrawAddress> withDrawAddressList = withDrawAddressRepository.findByAddressAndUserIdAndTypeAndStatus(address, user.getUserId(), walletType, 1);
        if (withDrawAddressList.size() > 0) {
            return new Resp(Resp.PARAM_ERROR, "该币种的地址已存在,请勿重复添加");
        }
        WithDrawAddress withDrawAddress = new WithDrawAddress();
        withDrawAddress.setUserId(user.getUserId());
        withDrawAddress.setType(walletType);
        withDrawAddress.setAddress(address);
        withDrawAddress.setAddressLabel(addressLabel);
        withDrawAddress.setStatus(1);//正常状态
        withDrawAddress.setAuthentication("已认证");
        withDrawAddress.setDefaultStatus(1); //非默认地址
        withDrawAddressRepository.save(withDrawAddress);
        return new Resp("添加成功");
    }

    @ApiOperation(value = "删除提币地址", notes = "需要提币地址id")
    @PostMapping("/remove_address")
    public Resp removeAddress(Long withDrawAddressId) {
        if (ParamUtil.isBlack(withDrawAddressId)) {
            return new Resp(Resp.PARAM_ERROR, "请选择提币地址");
        }
        WithDrawAddress withDrawAddress = withDrawAddressRepository.findOne(withDrawAddressId);
        withDrawAddress.setStatus(2);
        withDrawAddressRepository.save(withDrawAddress);
        return new Resp("删除成功");
    }


    /**
     * @author drj
     * @date 2018/07/12 18:55
     * @Description:排序工具类
     */
    private static void ListSort(List<WalletRecordVo> list) {
        Collections.sort(list, new Comparator<WalletRecordVo>() {
            @Override
            public int compare(WalletRecordVo o1, WalletRecordVo o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                try {
                    Date dt1 = format.parse(o1.getCreateDate() + "");
                    Date dt2 = format.parse(o2.getCreateDate() + "");
                    if (dt1.getTime() < dt2.getTime()) {
                        return 1;
                    } else if (dt1.getTime() > dt2.getTime()) {
                        return -1;
                    } else {
                        return 0;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });

    }


}
